package com.ansion.commonchat.startup.workmanager.bwork.impl.mode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanghongjie on 2023/5/5
 * Describe : 等同于 Database WorkTag 表的 API实现
 */
public class BWorkTagImpl implements BWorkTagDao {
    private WorkDataCache workDataCache;
    private final List<BWorkTag> tags = new ArrayList<>();
    private final Map<String, List<String>> idsForTag = new HashMap<>();
    private final Map<String, List<String>> tagsForId = new HashMap<>();
    private final Object mLock = new Object();

    public BWorkTagImpl(WorkDataCache workDataCache) {
        this.workDataCache = workDataCache;
    }


    @Override
    public void insert(BWorkTag workTag) {
        synchronized (mLock) {
            // 原始数据
            tags.add(workTag);
            // key 为 tag ， value 为 ids
            List<String> ids = idsForTag.get(workTag.tag);
            if (ids == null) {
                ids = new ArrayList<>();
                idsForTag.put(workTag.tag, ids);
            }
            ids.add(workTag.workSpecId);
            // key 为 id ， value 为 tags
            List<String> tags = tagsForId.get(workTag.workSpecId);
            if (tags == null) {
                tags = new ArrayList<>();
                tagsForId.put(workTag.workSpecId, tags);
            }
            tags.add(workTag.tag);
        }
    }

    @Override
    public List<String> getWorkSpecIdsWithTag(String tag) {
        List<String> list = idsForTag.get(tag);
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    @Override
    public List<String> getTagsForWorkSpecId(String id) {
        List<String> list = tagsForId.get(id);
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    @Override
    public void logout() {
        synchronized (mLock) {
            tags.clear();
            idsForTag.clear();
            tagsForId.clear();
        }
    }
}
